import React, { useState, useCallback, useRef, useMemo, useEffect } from 'react';
import SmartModal from '@/components/smartmodal';
import type { ModalProps } from 'antd/lib/modal';
import { GridCellEditWrapper } from '..';
import { getGantPopupContainer } from '@/utils/utils';
import { BaseSelect } from '../loupeselect';
import { EditStatus } from 'gantd';

export interface ModalWrapperProps extends Omit<ModalProps, 'visible' | 'onOk' | 'onCancel'> {
  /**
   * 触发弹窗的按钮文本或React节点
   */
  triggerText?: React.ReactNode;

  /**
   * 自定义触发按钮属性
   */
  triggerButtonProps?: React.ButtonHTMLAttributes<HTMLButtonElement> & {
    type?: 'primary' | 'ghost' | 'dashed' | 'link' | 'text' | 'default';
  };

  /**
   * 弹窗标题
   */
  title: React.ReactNode;

  /**
   * 弹窗宽度
   */
  width?: number | string;

  /**
   * 弹窗内容
   */
  children: React.ReactNode;

  /**
   * 确认按钮文本
   */
  okText?: React.ReactNode;

  /**
   * 取消按钮文本
   */
  cancelText?: React.ReactNode;

  /**
   * 值改变回调，通常连接到表单的onChange
   */
  onChange?: (value: any) => void;

  /**
   * 当前值
   */
  value?: any;

  /**
   * 禁用状态
   */
  disabled?: boolean;

  /**
   * 确认前处理函数，返回Promise，resolve时关闭弹窗，reject时保持弹窗
   */
  beforeOk?: (value: any) => Promise<any>;

  /**
   * 确认按钮加载状态
   */
  confirmLoading?: boolean;

  /**
   * 弹窗最小高度
   */
  minHeight?: number;

  /**
   * 弹窗最小宽度
   */
  minWidth?: number;

  /**
   * 弹窗状态参数，用于控制弹窗尺寸
   */
  itemState?: { width: number; height: number };

  /**
   * 底部左侧额外内容
   */
  footerLeftExtra?: React.ReactNode;

  /**
   * 底部右侧额外内容
   */
  footerRightExtra?: React.ReactNode;

  /**
   * 弹窗z-index
   */
  zIndex?: number;

  /**
   * 弹窗id
   */
  id?: string;

  /**
   * 失去焦点回调
   */
  onBlur?: () => void;

  /**
   * 聚焦回调
   */
  onFocus?: () => void;

  /**
   * 子组件props
   */
  childProps?: any;

  /**
   * 获取前一个props数据
   */
  getPrevPropsData?: () => Promise<any>;
}

export interface ModalWrapperRef {
  /**
   * 打开弹窗
   */
  open: () => void;

  /**
   * 关闭弹窗
   */
  close: () => void;
}

const ModalWrapper = (props: ModalWrapperProps) => {
  const {
    triggerText = '打开',
    triggerButtonProps,
    title = '默认弹窗',
    width = 1200,
    children,
    childProps = {},
    okText = '确定',
    cancelText = '取消',
    onChange,
    value,
    disabled = false,
    beforeOk,
    confirmLoading: propConfirmLoading,
    minHeight,
    minWidth,
    itemState = { width: 1200, height: 720 },
    footerLeftExtra,
    footerRightExtra,
    zIndex = 1000,
    id = 'modalWrapper',
    onBlur,
    getPrevPropsData,
    ...modalProps
  } = props;

  // 前置数据
  const [prevData, setPrevData] = useState<any>(null);

  useEffect(() => {
    if (getPrevPropsData) {
      getPrevPropsData().then((res: any) => {
        setPrevData(res);
      });
    }
  }, [getPrevPropsData]);

  const [visible, setVisible] = useState(false);
  //改变弹窗状态
  const changeVisibleState = useCallback((visible = false) => {
    setVisible(visible);
  }, []);
  const [innerValue, setInnerValue] = useState<any>(value);
  const [confirmLoading, setConfirmLoading] = useState(false);

  // 添加对子组件的引用
  const childrenRef = useRef<any>(null);

  // 内部值与外部值同步
  React.useEffect(() => {
    setInnerValue(value);
  }, [value]);

  // 打开弹窗
  // const handleOpen = useCallback(() => {
  //   if (!disabled) {
  //     setVisible(true);
  //   }
  // }, [disabled]);

  // 关闭弹窗
  const handleClose = useCallback(() => {
    setVisible(false);
  }, []);

  // // 暴露实例方法
  // useImperativeHandle(ref, () => ({
  //   open: handleOpen,
  //   close: handleClose
  // }));

  // 确认
  const handleOk = useCallback(async () => {
    try {
      // 尝试从子组件引用中获取值
      const childValue =
        childrenRef.current && typeof childrenRef.current.getSelectGrid === 'function'
          ? childrenRef.current.getSelectGrid()
          : innerValue;
      if (beforeOk) {
        setConfirmLoading(true);
        const processedValue = await beforeOk(childValue);
        if (onChange) {
          onChange(processedValue);
        }
      } else if (onChange) {
        onChange(childValue);
      }

      setConfirmLoading(false);
      handleClose();
    } catch (error) {
      console.error('Modal confirmation error:', error);
      setConfirmLoading(false);
    }
  }, [onChange, innerValue, beforeOk, handleClose]);

  // 取消
  const handleCancel = useCallback(() => {
    setInnerValue(value); // 重置为外部值
    handleClose();
  }, [value, handleClose]);

  // // 创建一个合并的ref函数，用于同时传递多个ref
  // const setChildRef = useCallback((element: any) => {
  //   childrenRef.current = element;
  // }, []);

  // 克隆子元素，传入值、onChange和ref
  const childrenWithProps = React.Children.map(children, (child) => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, {
        propsRef: childrenRef, // 传递ref给子组件
        prevData: prevData,
      });
    }
    return child;
  });

  // 处理弹窗大小变化
  const handleSizeChange = useCallback((width, height) => {
    // 如果需要处理尺寸变化的逻辑，可以在这里添加
  }, []);

  const foucsRef = useRef(true);

  const selectBlur = useCallback(() => {
    setTimeout(() => {
      if (foucsRef.current) return;
      onBlur && onBlur();
    }, 20);
  }, [onBlur]);

  const selectProps = useMemo(() => {
    return {
      isGrid: true,
      showArrow: false,
      readOnly: true,
      allowClear: true,
      useStorage: false,
      edit: EditStatus.EDIT,
      autoFocus: true,
      defaultParams: {
        activeStatus: 'CURRENT',
      },
    };
  }, []);

  return (
    <>
      <GridCellEditWrapper autoFocus onBlur={selectBlur} visible={visible}>
        <BaseSelect
          getPopupContainer={getGantPopupContainer}
          value={value}
          multiple={false}
          valueProp={'partNameZh'}
          // multiple={multiple}
          labelProp={'partNameZh'}
          componentType={undefined}
          // onChange={onChange}
          onLoupeClick={changeVisibleState.bind(null, true)}
          // onApiRef={(ref: any) => (selectApiRef.current = ref)}
          onBlur={() => {
            foucsRef.current = false;
          }}
          onFocus={() => {
            foucsRef.current = true;
          }}
          {...selectProps}
        />
        <SmartModal
          id={id}
          title={title}
          visible={visible}
          onOk={handleOk}
          onCancel={handleCancel}
          itemState={itemState}
          minWidth={minWidth}
          minHeight={minHeight}
          zIndex={zIndex}
          footerLeftExtra={footerLeftExtra}
          footerRightExtra={footerRightExtra}
          okText={okText}
          cancelText={cancelText}
          confirmLoading={propConfirmLoading !== undefined ? propConfirmLoading : confirmLoading}
          onSizeChange={handleSizeChange}
          destroyOnClose
          {...modalProps}
        >
          {childrenWithProps}
        </SmartModal>
      </GridCellEditWrapper>
    </>
  );
};

export default ModalWrapper;
